package com.moonbird.springboot.service;

import com.moonbird.springboot.DTO.Result;
import com.moonbird.springboot.mapper.UserMapper;
import com.moonbird.springboot.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public Result<String> login(User user) {
        // 查询数据库，检查是否存在具有相同用户名和密码的用户
        User dbUser = userMapper.findByUsernameAndPassword(user.getUsername(), user.getPassword());
        System.out.println("dbUser: " + dbUser);
        if (dbUser != null) {
            // 登录成功
            return Result.success(user.getId()+"");
        } else {
            // 登录失败
            return Result.fail("用户名或密码错误");
        }
    }

    public Result<String> register(User user) {
        if(!userMapper.findByUsername(user.getUsername())) {
            userMapper.insert(user);
        }else {
            return Result.fail("用户名已存在");
        }
        return Result.success("注册成功");
    }

    public Result<String> updatePassword(User user) {

        // 查询数据库，检查是否存在具有相同用户名的用户
        boolean dbUser = userMapper.findByUsername(user.getUsername());

        if (dbUser) {
            // 修改密码
            userMapper.updatePassword(user.getPassword(), user.getUsername());
            return Result.success("密码修改成功");
        } else {
            // 用户名不存在
            return Result.fail("用户名不存在");
        }
    }

    public Result<String> login1(User user) {
        if (user.getUsername().equals("admin") && user.getPassword().equals("admin")) {
            return Result.success("admin");
        } else {
            return Result.fail("用户名或密码错误");
        }
    }
}